package service

import (
	"fmt"
	"log"

	"github.com/beego/beego/v2/core/config"
	"github.com/casbin/casbin/v2"
	xormadapter "github.com/casbin/xorm-adapter/v2"
	_ "github.com/go-sql-driver/mysql"
)

var Enforcer *casbin.Enforcer

func CasBinSetup() {
	conf, err := config.NewConfig("ini", "conf/app.conf")
	if err != nil {
		log.Fatal("配置文件载入错误")
	}

	dbSection, err := conf.GetSection("db")
	if err != nil {
		log.Fatal("配置文件载入错误-数据库-section载入失败")
	}

	dbHost := dbSection["db_host"]
	dbPort := dbSection["db_port"]
	dbUser := dbSection["db_user"]
	dbPass := dbSection["db_pass"]
	dbName := dbSection["db_name"]

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", dbUser, dbPass, dbHost, dbPort, dbName)

	//log.Println("数据库DSN: " + dsn)

	a, err := xormadapter.NewAdapter("mysql", dsn, true)
	if err != nil {
		log.Printf("连接数据库错误: %v", err)
		return
	}
	e, err := casbin.NewEnforcer("conf/rbac_models.conf", a)
	if err != nil {
		log.Printf("初始化casbin错误: %v", err)
		return
	}

	Enforcer = e
}
